/*
Copyright (c) [2019年5月1日] [吴超]
[MBT_Studio] is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
		 http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
#include "stdafx.h"
#include "节点数据操作.h"
#include "节点数据声明.h"

#include <matXX.h>

static float32 f_从骨骼更新骨节(S_物体* 根骨骼, const float32* 骨骼长度, const vec3& 父坐标, const vec4& 父旋转, S_物体** 骨干, S_物体** 骨节) {
	float32 size = 1.0;


	uint32 num = 根骨骼->m_子物体.size();
	for (uint32 i = 0; i < num; ++i) {
		S_物体* 骨骼 = 根骨骼->m_子物体[i];
		auto* bones = f_ob_get骨骼数据(骨骼);

		uint32 id = 骨骼->m_实例ID;
		骨干[id]->f_set位置(父坐标, 0);
		骨干[id]->m_实例ID = id;


		vec4 q = f_graph_quat相乘(父旋转, bones->m_旋转);
		vec3 骨骼位移 = f_graph_quat反向变换坐标(q, DEF_骨骼朝向) * bones->m_长度;
		骨骼位移 += 父坐标;
		骨节[id]->f_set位置(骨骼位移, 0);

		size = DEF_Max(bones->m_长度 * 0.1, size);

		float32 骨节大小 = f_从骨骼更新骨节(骨骼, 骨骼长度, 骨骼位移, q, 骨干, 骨节);
		骨节[id]->f_set缩放(vec3{ 骨节大小 ,骨节大小, 骨节大小});
		骨节[id]->m_实例ID = id;
	}

	return size;
}



void f_NODE_BE_从骨骼更新骨节(S_物体* 骨架, S_物体** 骨干, S_物体** 骨节) {
	S_骨架* 骨架数据 = f_ob_from骨架(骨架);
	float32* 骨骼长度 = f_buf_F32_ptr(骨架数据->m_骨骼长度);

	uint32 num = 骨架->m_子物体.size();
	uint32 根骨节id = 骨架数据->m_骨头数量;
	for (uint32 i = 0; i < num; ++i) {
		S_物体* 骨骼 = 骨架->m_子物体[i];
		auto* bones = f_ob_get骨骼数据(骨骼);

		uint32 id = 骨骼->m_实例ID;
		//Mat44f mat = 父矩阵 * f_mat44_构建XYZ变换矩阵(骨骼->m_变换);
		
		//骨干[id]->f_set位置(骨骼->m_变换.location, 0);
		骨干[id]->m_实例ID = id;

		骨节[根骨节id + i]->f_set位置(骨骼->m_变换.location, 0);
		骨节[根骨节id + i]->f_set缩放(vec3{ 1.0f, 1.0f, 1.0f });
		骨节[根骨节id + i]->m_实例ID = id;


		骨骼长度[id] = bones->m_长度;

		vec3 骨骼位移 = f_graph_quat反向变换坐标(bones->m_旋转, DEF_骨骼朝向) * bones->m_长度;
		//骨骼位移 += 骨骼->m_变换.location;
		骨节[id]->f_set位置(骨骼位移, 0);

		float32 骨节大小 = f_从骨骼更新骨节(骨骼, 骨骼长度, 骨骼位移, bones->m_旋转, 骨干, 骨节);
		骨节[id]->f_set缩放(vec3{ 骨节大小 ,骨节大小, 骨节大小 });
		骨节[id]->m_实例ID = id;
	}
}

void f_NODE_BE_从骨节构建骨骼(S_物体* 骨架, S_物体** 骨干, S_物体** 骨节) {
	S_骨架* 骨架数据 = f_ob_from骨架(骨架);
	float32* 骨骼长度 = f_buf_F32_ptr(骨架数据->m_骨骼长度);



}


void f_NDE_解算IK(S_物体* 根骨骼) {
	S_骨架* 骨骼 = 根骨骼->m_骨架;

	for (uint32 i = 0; i < 骨骼->m_IK数量; ++i) {
		骨骼->m_IK[i]->m_始端;
		for (uint32 k = 0; k < 骨骼->m_IK[i]->m_深度; ++k) {

		}
	}
}

int32 f_NE_get着色器节点树ID(void* tree) {
	uint32 num = S_节点数据::g_着色节点树.size();
	for (uint32 i = 0; i < num; ++i) {
		if (S_节点数据::g_着色节点树[i].m_Ptr == tree) {
			return i;
		}
	}
	return -1;
}

